<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="不良事件详情"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canRecall" @click="recall">撤回</el-button>
          <el-button v-if="canApprove" @click="btnFlow('approve')"
            >批准</el-button
          >
          <el-button v-if="canReject" @click="btnFlow('reject')"
            >驳回</el-button
          >
          <el-button v-if="canRefuse" @click="btnFlow('refuse')"
            >拒绝</el-button
          >
          <el-button @click="salesReview" v-if="canSalesReview">销审</el-button>
        </template>
        <!--基础信息-->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="baseInfoList"></basic-information>
          </div>
        </div>
        <!-- 不良事件情况 -->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('adverseEventInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="adverseEventInfoList"></basic-information>
          </div>
        </div>

        <!-- 使用信息 -->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('useInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="useInfoInfoList"></basic-information>
          </div>
        </div>

        <!-- 初步原因分析及处置 -->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('preliminaryAnalysisInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="preliminaryAnalysisInfoList"
            ></basic-information>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 修改 -->
    <modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
    />
  </div>
</template>

<script setup>
import {
  getAdverseEventById,
  printAdverseEvent,
  submitAdverseEvent,
  approveAdverseEvent,
  rejectAdverseEvent,
  refuseAdverseEvent,
  recallAdverseEvent,
  salesReviewAdverseEvent,
} from '@/api/quality.js'
import BasicInformation from '@/components/BasicInformation/index'
import modify from './modify'
import PageTable from '@/components/PageTable/index'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id'])

const baseInfoList = reactive({
  data: [],
  fieldList: [
    { label: '设备', value: 'deviceName', type: 'text' },
    { label: '使用部门', value: 'deviceDeptName', type: 'text' },
    { label: '设备位置', value: 'deviceAddress', type: 'text' },
    { label: 'SN', value: 'deviceSn', type: 'text' },
    { label: '设备编码', value: 'deviceCode', type: 'text' },
    { label: '产品名称', value: 'productName', type: 'text' },
    { label: '注册证号', value: 'registerNo', type: 'text' },
    { label: '规格', value: 'model', type: 'text' },
    { label: '生产批号', value: 'batchNumber', type: 'text' },
    { label: '生产日期', value: 'productionDate', type: 'text' },
    { label: '失效日期', value: 'validityDate', type: 'text' },
  ],
})
const adverseEventInfoList = reactive({
  data: [],
  fieldList: [
    { label: '事件发生时间', value: 'happenTime', type: 'text' },
    { label: '发现获知时间', value: 'informedTime', type: 'text' },
    { label: '伤害', value: 'hurtTypeValue', type: 'text' },
    {
      label: '伤害表现',
      value: 'hurtPerformance',
      type: 'popover',
    },
    {
      label: '器械故障表现',
      value: 'fault',
      type: 'popover',
    },
    { label: '姓名', value: 'name', type: 'text' },
    { label: '出生日期', value: 'birthDate', type: 'text' },
    { label: '年龄', value: 'age', type: 'text' },
    { label: '性别', value: 'sexValue', type: 'text' },
    { label: '病历号', value: 'medicalRecordNo', type: 'text' },
    {
      label: '既往病史',
      value: 'pastMedicalHistory',
      type: 'popover',
    },
  ],
})
const useInfoInfoList = reactive({
  data: [],
  fieldList: [
    { label: '器械使用时间', value: 'useTime', type: 'text' },
    { label: '使用场所', value: 'useAddressTypeValue', type: 'text' },
    { label: '场所名称', value: 'addressName', type: 'text' },
    {
      label: '预期治疗疾病或作用',
      value: 'effect',
      type: 'popover',
    },
    { label: '使用过程', value: 'process', type: 'popover' },
    {
      label: '合并用药/械情况说明',
      value: 'consolidation',
      type: 'popover',
    },
  ],
})
const preliminaryAnalysisInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '事件原因分析',
      value: 'causeAnalysisTypeValue',
      type: 'popover',
    },
    {
      label: '事件原因分析描述',
      value: 'causeAnalysisDescribe',
      type: 'popover',
    },
    {
      label: '初步处置情况',
      value: 'handleSituation',
      type: 'popover',
    },
  ],
})
const modifyInfo = reactive({
  visible: false,
  id: '',
  title: '',
})
const affairTableInfo = reactive({
  api: orderOpAffairAll,
  query: {
    //数字字典单据类型 不良事件：51
    orderType: 51,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('adverseEvent:print') && baseInfoList.data.status === 3
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('adverseEvent:submit') &&
    (baseInfoList.data.status === 1 || baseInfoList.data.status === 5)
  )
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('adverseEvent:update') &&
    (baseInfoList.data.status === 1 || baseInfoList.data.status === 5)
  )
})
const canApprove = computed(() => {
  return (
    proxy.$permission('adverseEvent:approve') &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_adverse_event_approval == 1 &&
    baseInfoList.data.status === 2
  )
})
const canReject = computed(() => {
  return (
    proxy.$permission('adverseEvent:reject') &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_adverse_event_approval == 1 &&
    baseInfoList.data.status === 2
  )
})
const canRefuse = computed(() => {
  return (
    proxy.$permission('adverseEvent:refuse') &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_adverse_event_approval == 1 &&
    baseInfoList.data.status === 2
  )
})
// 撤回
const canRecall = computed(() => {
  return (
    proxy.$permission('adverseEvent:recall') &&
    (baseInfoList.data.status === 2 ||
      (baseInfoList.data.status === 3 &&
        proxy.$store.state.permission.systemConfig
          .allow_asset_adverse_event_approval == 0))
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('adverseEvent:salesReview') &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_adverse_event_approval != 0 &&
    baseInfoList.data.status === 3
  )
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => modifyInfo.visible,
  (value) => {
    if (!value) {
      getMain()
    }
  }
)

onMounted(() => {
  getMain()
})

//打印
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'adverseEventDetail',
    deptId: props.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: props.id,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: props.id,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
//修改
function update() {
  modifyInfo.id = baseInfoList.data.id
  modifyInfo.title = '修改不良事件'
  modifyInfo.visible = true
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'adverseEvent',
    orderIds: [baseInfoList.data.id],
  }
  submitAdverseEvent(data).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
// 按钮审批原因弹窗
function btnFlow(code) {
  const row = baseInfoList.data
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approveAdverseEvent
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        refreshDetail()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAdverseEvent
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAdverseEvent
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          refreshDetail()
        }
      })
    })
}
// 撤回
function recall() {
  recallAdverseEvent([baseInfoList.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview() {
  salesReviewAdverseEvent([baseInfoList.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function returnBack() {
  emit('returnBack', false)
}
function refreshDetail() {
  getMain()
}
function getMain() {
  getAdverseEventById(props.id).then((resp) => {
    if (resp && resp.success) {
      baseInfoList.data = resp.data
      adverseEventInfoList.data = resp.data
      useInfoInfoList.data = resp.data
      preliminaryAnalysisInfoList.data = resp.data
    }
  })
}
</script>

<style scoped></style>
